package crp.core.resource.domain.services;

import com.qwlabs.panache.Ranged;
import crp.core.course.domain.models.CourseEntity;
import crp.core.resource.domain.models.CourseResourceCount;
import crp.core.resource.domain.models.CourseResourceEntity;
import crp.core.resource.domain.models.ResourceEntity;
import crp.core.resource.domain.models.ResourceQuery;
import crp.core.resource.domain.repositories.CourseResourceRepository;
import crp.core.resource.domain.repositories.ResourceRepository;
import crp.core.shared.PublicStatus;
import crp.core.shared.PublishStatus;
import io.quarkus.panache.common.Range;

import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import java.util.Collection;
import java.util.Set;
import java.util.stream.Stream;

@ApplicationScoped
public class ResourceSearcher {
    private final ResourceRepository resourceRepository;
    private final CourseResourceRepository courseResourceRepository;

    @Inject
    public ResourceSearcher(ResourceRepository resourceRepository,
                            CourseResourceRepository courseResourceRepository) {
        this.resourceRepository = resourceRepository;
        this.courseResourceRepository = courseResourceRepository;
    }

    public Stream<ResourceEntity> find(ResourceQuery filter) {
        return resourceRepository.find(filter);
    }

    public Ranged<ResourceEntity> by(Range range) {
        return Ranged.of(resourceRepository.findAll(), range);
    }

    public Stream<ResourceEntity> byIds(Collection<String> ids) {
        return resourceRepository.findByIds(ids);
    }

    public Stream<CourseResourceCount> publicCountByCourseIds(Set<String> courseIds) {
        return courseResourceRepository.countByCourseIds(courseIds, PublicStatus.PUBLIC);
    }

    public Stream<CourseResourceCount> publishedCountByCourseIds(Set<String> courseIds) {
        return courseResourceRepository.countByCourseIds(courseIds, PublishStatus.PUBLISHED);
    }

    public Stream<CourseResourceCount> countByCourseIds(Set<String> courseIds) {
        return courseResourceRepository.countByCourseIds(courseIds);
    }

    public Stream<CourseEntity> findCoursesByResourceId(String resourceId) {
        return courseResourceRepository.findByResourceIds(Set.of(resourceId))
                .map(CourseResourceEntity::getCourse);
    }
}
